package com.concurrent.demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date 2020/7/8 15:03
 * @Author admin
 * @Description
 */
public class LockDemo {

    // 创建锁与条件变量
    private final Lock lock
            = new ReentrantLock();
    private final Condition done
            = lock.newCondition();
    public String response = null;
    // 调用方通过该方法等待结果
    void get(int timeout){
        long start = System.nanoTime();
        lock.lock();
        try {
            while (!isDone()) {
                System.out.println("当前线程: "+Thread.currentThread().getName());
                try {
                    done.await();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("当前线程wait: "+Thread.currentThread().getName());
                long cur=System.nanoTime();
                if (isDone() ||
                        cur-start > timeout){
                    break;
                }
            }
        } finally {
            System.out.println("unlock");
            lock.unlock();
        }

    }
    // RPC结果是否已经返回
    boolean isDone() {
        return response != null;
    }
    // RPC结果返回时调用该方法
    private void doReceived(String res) {
        lock.lock();
        try {
            response = res;
            done.signalAll();

        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        LockDemo lockDemo = new LockDemo();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lockDemo.doReceived("666");
            }
        });
        thread1.start();
        lockDemo.get(1);

    }

    private String name;
    protected void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}
